package org.jeecg.modules.demo.ddyht.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.ddyht.entity.DdygCustom;
import org.jeecg.modules.demo.ddyht.entity.DdygSupplier;
import org.jeecg.modules.demo.ddyht.service.IDdygSupplierService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.po.JxcCzrz;
import org.jeecg.modules.demo.jxcx.po.JxcPayinfor;
import org.jeecg.modules.demo.jxcx.po.JxcSupplier;
import org.jeecg.modules.demo.jxcx.service.JxcCzrzService;
import org.jeecg.modules.demo.jxcx.service.JxcPayinforService;
import org.jeecg.modules.demo.jxcx.service.JxcSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 应付明细
 * @Author: jeecg-boot
 * @Date:   2025-02-23
 * @Version: V1.0
 */
@Api(tags="应付明细")
@RestController
@RequestMapping("/ddyht/jxcSupplier")
@Slf4j
public class DdygSupplierController extends JeecgController<DdygSupplier, IDdygSupplierService> {
	@Autowired
	private IDdygSupplierService ddygSupplierService;
	@Autowired
	private JxcSupplierService jxcSupplierService;
	@Autowired
	private JxcPayinforService jxcPayinforService;
	@Autowired
	private JxcCzrzService jxcCzrzService;
     @Autowired
     private YueController yueController;
	/**
	 * 分页列表查询
	 *
	 * @param ddygSupplier
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "应付明细-分页列表查询")
	@ApiOperation(value="应付明细-分页列表查询", notes="应付明细-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DdygSupplier>> queryPageList(DdygSupplier ddygSupplier,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		QueryWrapper<DdygSupplier> queryWrapper = QueryGenerator.initQueryWrapper(ddygSupplier, req.getParameterMap());
		Page<DdygSupplier> page = new Page<DdygSupplier>(pageNo, pageSize);
		IPage<DdygSupplier> pageList = ddygSupplierService.page(page, queryWrapper);
		List<DdygSupplier> company = ddygSupplierService.getBycompany(ddygSupplier.getUsername());
		if (StringUtils.isNotBlank(ddygSupplier.getType1())) {
			List<DdygSupplier> list = new ArrayList<>();
			String type1 = ddygSupplier.getType1();
			if (type1.equals("only")) {
				if (ddygSupplier.getType2().equals("traner")) {
					if (StringUtils.isBlank(ddygSupplier.getType3())){
						int size = company.size();
						int page2 = (size + 9) / 10;
						pageList.setTotal(size);
						pageList.setPages(page2);
						pageList.setRecords(company);
						return Result.OK(pageList);
					}
					String type3 = ddygSupplier.getType3();
					for (int i = 0; i < company.size(); i++) {
						if (StringUtils.containsIgnoreCase(company.get(i).getName(), type3)) {
							list.add(company.get(i));
						}
					}
				}
				int size = list.size();
				int page2 = (size + 9) / 10;
				pageList.setTotal(size);
				pageList.setPages(page2);
				pageList.setRecords(list);
				return Result.OK(pageList);
			}
		}
		int size = company.size();
		int page2 = (size + 9) / 10;
		pageList.setTotal(size);
		pageList.setPages(page2);
		pageList.setRecords(company);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param ddygSupplier
	 * @return
	 */
	@AutoLog(value = "应付明细-添加")
	@ApiOperation(value="应付明细-添加", notes="应付明细-添加")
//	@RequiresPermissions("ddyht:jxc_supplier:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DdygSupplier ddygSupplier) {
		String companyId  = ddygSupplier.getUsername();
		String creatTime = ddygSupplier.getCreateTime();
		String name = ddygSupplier.getName();
		String amount = ddygSupplier.getAmount();
		LocalDateTime now = LocalDateTime.now();
		// 定义日期时间格式
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime dateTime = LocalDateTime.parse(creatTime, formatter);
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		// 格式化当前的日期和时间
		String id = now.format(formatter2);
		DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		String formattedDateTime = now.format(formatter3);
		DdygSupplier existingSupplier = ddygSupplierService.getBycompanyAndName(companyId, name);
		if (existingSupplier == null){
			DdygSupplier ddygSupplier1 = new DdygSupplier();
			ddygSupplier1.setId(id);
			ddygSupplier1.setCreateTime(formattedDateTime);
			ddygSupplier1.setName(name);
			ddygSupplier1.setCompanyId(companyId);
			ddygSupplier1.setAmount(amount);
			ddygSupplierService.save(ddygSupplier1);
		}else {
//			DdygSupplier ddygSupplier1 = ddygSupplierService.getBycompanyAndName(companyId,name);
			existingSupplier.setAmount(new BigDecimal(existingSupplier.getAmount()).add(new BigDecimal(amount)).toString());
			existingSupplier.setCreateTime(formattedDateTime);
//			ddygSupplierService.updateById(ddygSupplier1);


			LambdaUpdateWrapper<DdygSupplier> wrapper = new LambdaUpdateWrapper<>();
			wrapper.eq(DdygSupplier::getCompanyId, existingSupplier.getCompanyId())
					.eq(DdygSupplier::getName, existingSupplier.getName());
			ddygSupplierService.update(existingSupplier, wrapper);
		}


		JxcCzrz jxcCzrz1 = new JxcCzrz();
		jxcCzrz1.setId(DdygPiciController.setczrzid(id));
		jxcCzrz1.setCompanyId(companyId);
		jxcCzrz1.setOtherid("应收应付-新增");
		jxcCzrz1.setOrstate("应付款-"+name);
		jxcCzrz1.setType("应付款-"+name);
		jxcCzrz1.setInfor("新增：+" + amount);
		jxcCzrz1.setCreatTime(dateTime.format(formatter3));
        yueController.setSupplier(jxcCzrz1,name,amount,"新增：+");
		jxcCzrzService.add(jxcCzrz1);

		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param ddygSupplier
	 * @return
	 */
	@AutoLog(value = "应付明细-编辑")
	@ApiOperation(value="应付明细-编辑", notes="应付明细-编辑")
	@RequiresPermissions("ddyht:jxc_supplier:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DdygSupplier ddygSupplier) {
		ddygSupplierService.updateById(ddygSupplier);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "应付明细-通过id删除")
	@ApiOperation(value="应付明细-通过id删除", notes="应付明细-通过id删除")
	@RequiresPermissions("ddyht:jxc_supplier:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		JxcSupplier byId = jxcSupplierService.getById(id);
		String other = byId.getName();
		String companyId = byId.getCompanyId();
		List<JxcPayinfor> List = jxcPayinforService.getByall(companyId,other,"1");
		for (int i = 0; i < List.size(); i++) {
			JxcPayinfor jxcPayinfor = List.get(i);
			jxcPayinforService.removeById(jxcPayinfor.getId());

			JxcCzrz jxcCzrz1 = new JxcCzrz();
			jxcCzrz1.setId(DdygPiciController.setczrzid(id));
			jxcCzrz1.setCompanyId(companyId);
			jxcCzrz1.setInfor("交易方:"+jxcPayinfor.getOther()+"金额:"+jxcPayinfor.getPayamount());
			jxcCzrz1.setType("供应商付款明细删除");
			R add1 = jxcCzrzService.add(jxcCzrz1);
		}
		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(companyId);
		jxcCzrz.setInfor("交易方:"+byId.getName()+"金额:"+byId.getAmount());
		jxcCzrz.setType("供应商删除");
		R add = jxcCzrzService.add(jxcCzrz);

		ddygSupplierService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "应付明细-批量删除")
	@ApiOperation(value="应付明细-批量删除", notes="应付明细-批量删除")
	@RequiresPermissions("ddyht:jxc_supplier:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		log.info("删除数据"+list);
		for (int i = 0; i < list.size(); i++) {
			String id = list.get(i);
			JxcSupplier byId = jxcSupplierService.getById(id);
			String other = byId.getName();
			String companyId = byId.getCompanyId();
			List<JxcPayinfor> List = jxcPayinforService.getByall(companyId,other,"1");
			for (int j = 0; j < List.size(); j++) {
				JxcPayinfor jxcPayinfor = List.get(j);
				jxcPayinforService.removeById(jxcPayinfor.getId());

				JxcCzrz jxcCzrz1 = new JxcCzrz();
				jxcCzrz1.setId(DdygPiciController.setczrzid(id));
				jxcCzrz1.setCompanyId(companyId);
				jxcCzrz1.setInfor("交易方:"+jxcPayinfor.getOther()+"金额:"+jxcPayinfor.getPayamount());
				jxcCzrz1.setType("供应商付款明细删除");
				R add1 = jxcCzrzService.add(jxcCzrz1);
			}
			JxcCzrz jxcCzrz = new JxcCzrz();
			jxcCzrz.setId(DdygPiciController.setczrzid(id));
			jxcCzrz.setCompanyId(companyId);
			jxcCzrz.setInfor("交易方:"+byId.getName()+"金额:"+byId.getAmount());
			jxcCzrz.setType("供应商删除");
			R add = jxcCzrzService.add(jxcCzrz);
		}

		this.ddygSupplierService.removeByIds(list);
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "应付明细-通过id查询")
	@ApiOperation(value="应付明细-通过id查询", notes="应付明细-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DdygSupplier> queryById(@RequestParam(name="id",required=true) String id) {
		DdygSupplier ddygSupplier = ddygSupplierService.getById(id);
		if(ddygSupplier ==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(ddygSupplier);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param ddygSupplier
    */
    @RequiresPermissions("ddyht:jxc_supplier:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DdygSupplier ddygSupplier) {
        return super.exportXls(request, ddygSupplier, DdygSupplier.class, "应付明细");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("ddyht:jxc_supplier:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DdygSupplier.class);
    }

}
